package com.mingqijia.gassafety.job.job;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.mapper.DtuDataStatisticsMapper;
import com.mingqijia.gassafety.job.service.RecordControllerService;
import com.mingqijia.gassafety.job.service.RecordDetectorService;
import com.mingqijia.gassafety.job.service.RecordDtuService;
import com.mingqijia.gassafety.job.service.RecordReceiverValveService;
import com.mingqijia.gassafety.job.service.impl.DtuDataStatisticsServiceImpl;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xhb
 * @version 1.0.0
 * @Description 设备记录历史数据处理
 * @createTime
 */
@Configuration
@EnableScheduling
@Slf4j
public class DeviceRecordHistoryJob {
    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    RecordControllerService recordControllerService;
    @Autowired
    RecordDetectorService recordDetectorService;
    @Autowired
    RecordReceiverValveService recordReceiverValveService;
    @Autowired
    RecordDtuService recordDtuService;

    /**
     * 0 0 0 0 * ? 每天0点运行
     */
    @XxlJob("deviceRecordHistory")
    public ReturnT<String> deviceRecordHistory(String param) {
        XxlJobLogger.log("XXLJOB-deviceRecordHistory start...");
        log.info("deviceRecordHistory--start--------");
        String key = Constants.DEVICE_RECORD_HISTORY;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    log.info("deviceRecordHistory--进入执行器--------");
                    execute();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("deviceRecordHistory-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("deviceRecordHistory-error:{}", e);
        }

        log.info("deviceRecordHistory--end--------");
        XxlJobLogger.log("XXLJOB-deviceRecordHistory end...");
        return ReturnT.SUCCESS;
    }

    private void execute() {
        int page = 0;
        int pageSize = 500;
        //查询控制器上报记录
        List<RecordController> list = recordControllerService.getPageList(page,pageSize);
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(RecordController::getId).collect(Collectors.toList());
            log.info("需要备份的ids:"+ids);
            //查询控制器上报记录对应的探头，设备，电磁阀记录列表
            List<RecordDetector> detectorList = recordDetectorService.getListByRecordId(ids);
            List<RecordReceiverValve> receiverList = recordReceiverValveService.getListByRecordId(ids);
            List<RecordDtu> dtuList = recordDtuService.getListByRecordId(ids);
            for (RecordController recordController : list) {
                recordControllerService.deviceRecordHandle(recordController,
                        detectorList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                        receiverList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                        dtuList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),page);
            }
            recordControllerService.deleteRecord(ids, detectorList, receiverList, dtuList, page);
            while (!list.isEmpty()) {
                //查询控制器上报记录
                list = recordControllerService.getPageList(page,pageSize);
                if (!CollectionUtils.isEmpty(list)) {
                    //查询控制器上报记录对应的探头，设备，电磁阀记录列表
                    List<Long> ids2 = list.stream().map(RecordController::getId).collect(Collectors.toList());
                    log.info("需要备份的ids:"+ids2);
                    List<RecordDetector> detectorList2 = recordDetectorService.getListByRecordId(ids2);
                    List<RecordReceiverValve> receiverList2 = recordReceiverValveService.getListByRecordId(ids2);
                    List<RecordDtu> dtuList2 = recordDtuService.getListByRecordId(ids2);
                    for (RecordController recordController : list) {
                        recordControllerService.deviceRecordHandle(recordController,
                                detectorList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                receiverList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                dtuList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),page);
                    }
                    recordControllerService.deleteRecord(ids2, detectorList2, receiverList2, dtuList2, page);
                }
            }
        }
    }
}
